<script>
import { parseSceneData } from '@/utils/scene-data'
import AddFile from '@/components/PopItems/add-file.vue'
import Detail from '@/views/energyConsumptionAnalysis/deviceMeterStatics/Detail.vue'
import { now, subtractDateStr, subtractHourStr } from '@/utils/date-utils'

export default {
  name: 'DeviceMeterStatics',
  components: { Detail, AddFile },
  data() {
    return {
      queryForm: {
        statisticsMode: 'hour', // hour:时，day:日,month: 月,year: 年,
        solidifyDateStart: null,
        solidifyDateEnd: null,
        page: 1,
        limit: 10
      },
      energyTypeList: [], //能耗类型
      deviceTypeList: [], //设备类型
      projectList: [],  // 项目树
      roomList: [],  // 空间树
      datePickerType: 'datetime',
      timeFormat: 'yyyy-MM-dd HH:mm:ss',
      tableLoading: false,
      list: [],
      total: 0,
      showImportDialog: false,
      importPopConfig: {
        width: '40%',
        hideFooterBtn: true,
        // 上传接口
        upLoadPath: '/energy-carbon/ecp-admin/deviceMeterStatics/upload',
        // 模板下载参数
        tplName: 'deviceRenderer'
      },
      showDetailDialog: false,
      detailItem: {},
      startTimeOption: {
        disabledDate: this.disabledStartDate
      },
      endTimeOption: {
        disabledDate: this.disabledEndDate
      }
    }
  },
  created() {
    this.$api.commonSelected({
      code: 'EnergyConsumptionTypeSelected'
    }).then(response => {
      this.energyTypeList = response.data
    })
    this.$api.commonSelected({
      code: 'SceneProjectSelected'
    }).then(response => {
      this.projectList = response.data
    })
    this.$api.dictList({
      codeList: ['ecp-admin.device.deviceType']
    }).then(response => {
      this.deviceTypeList = response.data['ecp-admin.device.deviceType']
    })
    this.statisticsModeChangeHandler()
    this.getList()
  },
  methods: {
    handleSizeChange(limit) {
      this.queryForm.limit = limit
      this.getList()
    },
    handleCurrentChange(page) {
      this.queryForm.page = page
      this.getList()
    },
    exportData() {
      this.$formatFile.downFilePost('/energy-carbon/ecp-admin/deviceMeterStatics/export', this.queryForm)
    },
    resetHandler() {
      this.queryForm = {
        statisticsMode: this.queryForm.statisticsMode,
        page: 1,
        limit: 10
      }
      this.getList()
    },
    getList() {
      this.tableLoading = true
      if (this.queryForm.roomInfo != null && this.queryForm.roomInfo.length > 0) {
        this.queryForm.sceneEdificeId = this.queryForm.roomInfo[0]
        if (this.queryForm.roomInfo.length > 1) {
          this.queryForm.sceneFloorId = this.queryForm.roomInfo[1]
        }
        if (this.queryForm.roomInfo.length > 2) {
          this.queryForm.sceneRoomId = this.queryForm.roomInfo[2]
        }
      } else {
        delete this.queryForm.sceneEdificeId
        delete this.queryForm.sceneFloorId
        delete this.queryForm.sceneRoomId
      }
      this.$api.deviceMeterStatistic.queryList(this.queryForm).then(response => {
        this.list = response.data.records
        this.total = response.data.total
      }).finally(() => this.tableLoading = false)
    },
    detailDialogHandler(row) {
      this.detailItem = Object.assign({}, row)
      this.showDetailDialog = true
    },
    disabledStartDate(time) {
      if (this.queryForm.solidifyDateEnd == null) {
        return false
      }
      let threshold = 0
      switch (this.queryForm.statisticsMode) {
        case 'hour':
          threshold = 8
          break
        case 'day':
          threshold = 32
          break
        case 'month':
          threshold = 366
          break
        case 'year':
          threshold = 365 * 3
          break
      }
      const date = new Date()
      date.setTime(Date.parse(this.queryForm.solidifyDateEnd) - threshold * 86400000)
      const result = time.getTime() > date.getTime() && time.getTime() < Date.parse(this.queryForm.solidifyDateEnd)
      return !result
    },
    disabledEndDate(time) {
      if (this.queryForm.solidifyDateStart == null) {
        return false
      }
      let threshold = 0
      switch (this.queryForm.statisticsMode) {
        case 'hour':
          threshold = 8
          break
        case 'day':
          threshold = 32
          break
        case 'month':
          threshold = 366
          break
        case 'year':
          threshold = 365 * 3
          break
      }
      const date = new Date()
      date.setTime(Date.parse(this.queryForm.solidifyDateStart) + threshold * 86400000)
      const result = time.getTime() > Date.parse(this.queryForm.solidifyDateStart) && time.getTime() < date.getTime()
      return !result
    },
    statisticsModeChangeHandler() {
      switch (this.queryForm.statisticsMode) {
        case 'hour':
          this.datePickerType = 'datetime'
          this.timeFormat = 'yyyy-MM-dd HH:mm:ss'
          this.queryForm.solidifyDateStart = subtractHourStr(new Date(), 1)
          this.queryForm.solidifyDateEnd = now()
          break
        case 'day':
          this.datePickerType = 'date'
          this.timeFormat = 'yyyy-MM-dd'
          this.queryForm.solidifyDateStart = subtractDateStr(new Date(), 1)
          this.queryForm.solidifyDateEnd = now()
          break
        case 'month':
          this.datePickerType = 'month'
          this.timeFormat = 'yyyy-MM'
          this.queryForm.solidifyDateStart = subtractDateStr(new Date(), 31)
          this.queryForm.solidifyDateEnd = now()
          break
        case 'year':
          this.datePickerType = 'year'
          this.timeFormat = 'yyyy'
          this.queryForm.solidifyDateStart = subtractDateStr(new Date(), 365)
          this.queryForm.solidifyDateEnd = now()
          break
      }
      this.getList()
    },
    projectChangeHandler(value) {
      if (value == null || value === '') {
        this.roomList = []
      } else {
        this.$api.sceneRoom.queryRoomList({
          sceneProjectId: value,
          sortColumn: 'floorName',
          sortOrder: 'asc'
        }).then(response => {
          this.roomList = parseSceneData(response.data)
        })
      }
    }
  }
}
</script>

<template>
  <div class="deviceMeterStatics">
    <el-form :model="queryForm" inline>
      <el-form-item>
        <el-radio-group v-model="queryForm.statisticsMode" @change="statisticsModeChangeHandler">
          <el-radio-button label="hour">按时</el-radio-button>
          <el-radio-button label="day">按日</el-radio-button>
          <el-radio-button label="month">按月</el-radio-button>
          <el-radio-button label="year">按年</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="开始时间" prop="solidifyDateStart">
        <el-date-picker v-model="queryForm.solidifyDateStart" :type="datePickerType"
                        :format="timeFormat"
                        :value-format="timeFormat"
                        :picker-options="startTimeOption"></el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="solidifyDateEnd">
        <el-date-picker v-model="queryForm.solidifyDateEnd" :type="datePickerType"
                        :format="timeFormat"
                        :value-format="timeFormat"
                        :picker-options="endTimeOption"></el-date-picker>
      </el-form-item>
      <el-form-item label="关键字" prop="deviceCodeOrName">
        <el-input v-model="queryForm.deviceCodeOrName" placeholder="请输入设备编码/设备名称" clearable />
      </el-form-item>
      <el-form-item label="能耗类型" prop="energyTypeId">
        <el-select v-model="queryForm.energyTypeId" clearable>
          <el-option v-for="item in energyTypeList" :key="item.id" :value="item.value" :label="item.label"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属项目" prop="sceneProjectId">
        <el-select v-model="queryForm.sceneProjectId" @change="projectChangeHandler" clearable>
          <el-option v-for="item in projectList" :key="item.id" :value="item.value" :label="item.label"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属场景" prop="roomInfo">
        <el-cascader v-model="queryForm.roomInfo" :options="roomList" placeholder="请选择" clearable
                     :props="{ checkStrictly: true }" />
      </el-form-item>
      <el-form-item label="设备类型" prop="deviceType">
        <el-select v-model="queryForm.deviceType" clearable>
          <el-option v-for="item in deviceTypeList" :key="item.id" :value="item.value" :label="item.label"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button size="small" @click="getList" type="primary" icon="el-icon-search">查询</el-button>
        <el-button size="small" @click="resetHandler" icon="el-icon-refresh-right">重置</el-button>
        <el-button size="small" @click="() => this.showImportDialog = true" type="primary" icon="el-icon-download">录入数据
        </el-button>
        <el-button size="small" @click="exportData" type="primary" icon="el-icon-upload2">导出</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="list" v-loading="tableLoading" element-loading-text="拼命加载中">
      <el-table-column prop="solidifyDateStr" label="时间" width="160" />
      <el-table-column prop="projectName" label="所属项目" />
      <el-table-column prop="sceneInfoName" label="所属场景" />
      <el-table-column prop="deviceCode" label="设备编码" />
      <el-table-column prop="deviceName" label="设备名称" />
      <el-table-column prop="deviceTypeName" label="设备类型" />
      <el-table-column prop="isFocusName" label="是否重点关注设备" />
      <el-table-column prop="energyTypeName" label="能耗类型" />
      <el-table-column prop="readMeterTagName" label="读表标识" />
      <el-table-column prop="meterValue" label="计量值" />
      <el-table-column prop="energyTypeUnit" label="单位" />
      <el-table-column label="操作">
        <template #default="{row}">
          <el-button v-if="queryForm.statisticsMode !== 'hour'" type="text" @click="detailDialogHandler(row)">读数详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination style="text-align: right;margin-top: 12px;"
                   v-if="total > 0"
                   ref="paginationRef"
                   background
                   :current-page="queryForm.currentPage"
                   :page-sizes="[10, 30, 50, 100, 200, 500]"
                   :page-size="queryForm.pageSize"
                   :layout="'total, sizes, prev, pager, next, jumper'"
                   :total="total"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"
    />
    <el-dialog title="手工导入" :visible.sync="showImportDialog" width="30%" :modal="false" destroy-on-close>
      <AddFile :pop-config="importPopConfig" />
    </el-dialog>
    <el-dialog title="读数详情" :visible.sync="showDetailDialog" width="50%" :modal="false" destroy-on-close>
      <Detail :device="detailItem" :date-type="queryForm.statisticsMode" />
    </el-dialog>
  </div>
</template>
<style lang="scss" scoped>
.deviceMeterStatics {
  background: #ffffff;
  padding: 26px;
  overflow-y: auto;
  max-height: calc(100vh - 130px);
}

.tag-container {
  display: flex;
  gap: 6px;

  .el-tag {
    cursor: pointer;
  }

}
</style>
